<template>
  <div class="page-common-layout project-initiation-container">
    <div class="initiation-header">
      {{ menuName }}
      <a-button icon="edit" v-action:xmlx_edit @click="handleEditor()">
        编辑
      </a-button>
    </div>
    <div class="initiation-main">
      <div class="introduce-container">
        <div class="base-info">
          <div class="data-item">
            <div class="label">项目类型：</div>
            <div class="value">
              {{ form.engTypeDesc }}
            </div>
          </div>
          <div class="data-item">
            <div class="label">立项类型：</div>
            <div class="value">{{ form.typeDesc }}</div>
          </div>
          <div class="data-item">
            <div class="label">省市县：</div>
            <div class="value">
              {{ form.workArea ? form.workArea.replace(/@/g, ">") : "" }}
            </div>
          </div>
          <div class="data-item">
            <div class="label">提交人：</div>
            <div class="value">{{ form.creator }}</div>
          </div>
          <div class="data-item">
            <div class="label">提交时间：</div>
            <div class="value">{{ form.createTime }}</div>
          </div>
        </div>
        <div class="remark">
          <div class="data-item">
            <div class="label">备注：</div>
            <div class="value">
              {{ form.remark }}
            </div>
          </div>
        </div>
      </div>
      <div class="file-container">
        <div class="name">文件：</div>
        <div class="tree-container">
          <a-empty v-if="treeData.length == 0" :description="false" />
          <a-tree
            v-else
            show-icon
            show-line
            :expanded-keys="expandedKeys"
            :auto-expand-parent="autoExpandParent"
            :selected-keys="selectedKeys"
            :tree-data="treeData"
            :replaceFields="{
              children: 'children',
              title: 'nodeName',
              key: 'uuid',
            }"
            @expand="onExpand"
            @select="onSelect"
          >
            <!-- 自定义图标 -->
            <template slot="custom" slot-scope="{ expanded }">
              <a-icon
                :type="expanded ? 'folder-open' : 'folder'"
                theme="filled"
              />
            </template>
            <template slot="title" slot-scope="{ nodeName }">
              <div class="custom-tree-title-warp">
                <div class="title" :title="nodeName">
                  {{ nodeName }}
                </div>
              </div>
            </template>
          </a-tree>
        </div>
        <div class="right-container">
          <div class="operate">
            <a-button
              type="primary"
              icon="download"
              @click="handleDownloadZip()"
              :loading="downloadLoading"
              :disabled="downloadLoading"
              v-action:xmlx_download
            >
              {{ downloadLoading ? "下载中" : "批量下载" }}
            </a-button>
          </div>
          <div class="table-container">
            <vxe-table
              ref="xTable"
              height="99%"
              align="left"
              show-overflow
              show-header-overflow
              border="inner"
              :data="tableData"
              :column-config="{ resizable: true }"
              size="small"
              :loading="loading"
            >
              <vxe-column type="seq" width="80" title="序号"></vxe-column>
              <vxe-column field="name" title="文件名称" min-width="200">
                <template #default="{ row }">
                  <div class="table-file-name">
                    <div
                      class="icon"
                      :class="[getFileIconName(row.name)]"
                    ></div>
                    <div class="name" @click="handelFileModal(row)">
                      {{ row.name }}
                    </div>
                  </div>
                </template>
              </vxe-column>
              <vxe-column field="creator" title="上传人"> </vxe-column>
              <vxe-column field="createTime" title="上传时间"> </vxe-column>
              <vxe-column title="操作" width="100">
                <template #default="{ row}">
                  <div class="files-icon">
                    <!-- 预览 -->
                    <a-tooltip placement="top">
                      <template slot="title">
                        预览
                      </template>
                      <a-icon
                        type="eye"
                        class="preview-btn"
                        @click="handelFileModal(row)"
                      />
                    </a-tooltip>
                    <!-- 下载 -->
                    <a-tooltip placement="top" v-action:xmlx_download>
                      <template slot="title">
                        下载
                      </template>
                      <a-icon
                        type="download"
                        class="download-btn"
                        @click="downloadFile(row)"
                      />
                    </a-tooltip>
                  </div>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </div>
      </div>
    </div>
    <!-- 多文件 -->
    <viewFileModal
      :visible.sync="viewFileModal.visible"
      :fileList="viewFileModal.fileList"
      :subtitle="viewFileModal.name"
      :replaceFields="{
        fileName: 'name',
      }"
    ></viewFileModal>
    <!-- 单文件 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>
    <!-- 编辑 -->
    <editorPage
      :key="editorPage.key"
      :visible.sync="editorPage.visible"
      :parameter="editorPage.source"
    ></editorPage>
  </div>
</template>

<script>
import { axios } from "@/utils/request";
import {
  addAttributeByKey,
  flatTreeData,
  _getUUID,
  getFileIconName,
} from "@/utils/util.js";
import { mapGetters } from "vuex";
import {
  getToken,
  downloadDfs,
  downLoadBatchFileByArraybuffer,
} from "@/utils/TopVUI";
//多文件预览
import viewFileModal from "@/components/extendCustom/view-file-modal";
//单文件预览
import previewModal from "@/pages/document/minio/previewModal";
//编辑
import editorPage from "./editorPage";
import { detailCanton } from "@/api/cantonManage";
export default {
  components: {
    viewFileModal,
    previewModal,
    editorPage,
  },
  data() {
    return {
      //列表
      loading: false,
      tableData: [],
      pager: {
        page: 1,
        pageSize: 50,
        total: 0,
      },
      //详情
      form: {},
      //左侧树
      expandedKeys: [],
      autoExpandParent: true,
      selectedKeys: [],
      treeData: [],
      currentTreeNode: {},
      //下载
      downloadLoading: false,
      //多文件预览
      viewFileModal: {
        name: "",
        visible: false,
        fileList: [],
      },
      //单文件预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //编辑
      editorPage: {
        visible: false,
        key: _getUUID(),
        source: {},
      },
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
    menuName() {
      let { title } = this.$route.meta;
      return title;
    },
  },
  mounted() {
    this.getData();
  },
  methods: {
    getFileIconName,
    async getData() {
      await this.getDetail();
      await this.getTreeData();
    },
    //编辑
    handleEditor() {
      this.editorPage.key = _getUUID();
      this.editorPage.source = this.form;
      this.editorPage.visible = true;
    },

    //下载压缩包
    handleDownloadZip() {
      let { uuid, nodeName } = this.currentTreeNode;
      this.downloadLoading = true;
      axios
        .post(
          `/probusiness/projectInitiationFile/exportZip?treeUuid=${uuid}`,
          {},
          {
            headers: {
              "Content-Type": "application/json",
            },
            apiType: "file",
            responseType: "arraybuffer",
          }
        )
        .then((data) => {
          downLoadBatchFileByArraybuffer(data, nodeName + ".zip");
        })
        .catch()
        .finally((_) => {
          this.downloadLoading = false;
        });
    },
    //查询详情
    getDetail() {
      detailCanton({
        code: "XMLX",
      })
        .then((res) => {
          this.form = {
            uuid: res.uuid,
            //项目类型
            engTypeDesc: res?.engTypeDesc,
            //区域
            workArea: res?.workArea,
            //立项类型
            typeDesc: res?.typeDesc,
            //备注
            remark: res.remark,
            //创建人
            creator: res.creator,
            //创建时间
            createTime: res.createTime,
          };
        })
        .catch((_) => {});
    },
    //查询树
    getTreeData() {
      axios
        .post(
          `/probusiness/projectInitiationTree/getTree`,
          {},
          {
            headers: {
              "Content-Type": "application/json;charset=UTF-8",
            },
          }
        )
        .then((res) => {
          let source = res?.data ?? [];
          let flatData = flatTreeData(source, "children");
          this.expandedKeys = flatData.map((v) => v.uuid).filter((v) => v);
          let filterData = addAttributeByKey(
            null,
            "scopedSlots",
            { icon: "custom" },
            source,
            "children"
          );
          this.treeData = filterData ?? [];
          if (!this.currentTreeNode.uuid) {
            this.currentTreeNode = filterData?.[0] ?? {};
          }
          this.selectedKeys = [this.currentTreeNode.uuid];
          this.getTableData();
        })
        .catch((_) => {});
    },
    //查询列表
    getTableData() {
      let { uuid } = this.currentTreeNode;
      this.loading = true;
      axios
        .post(
          `/probusiness/projectInitiationFile/getList`,
          { treeUuid: uuid },
          {
            headers: {
              "Content-Type": "application/json;charset=UTF-8",
            },
          }
        )
        .then((res) => {
          this.tableData = res ?? [];
        })
        .catch((_) => {
          this.tableData = [];
        })
        .finally((_) => {
          this.loading = false;
        });
    },
    //监听树形选择
    onSelect(selectedKeys, info) {
      let { uuid } = info.node.dataRef;
      this.currentTreeNode = info.node.dataRef;
      this.selectedKeys = [uuid];
      this.getTableData();
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys;
      this.autoExpandParent = false;
    },
    //预览
    handelFileModal(row) {
      const fileList = JSON.parse(row?.fileAddress ?? "[]");
      if (fileList.length == 0) {
        return;
      } else if (fileList.length == 1) {
        let { url } = fileList?.[0] ?? {};
        this.previewModal.loading = true;
        this.$refs.previewModal.type = "file";
        this.$refs.previewModal.fileUrl =
          this.kkFileView +
          "/onlinePreview?url=" +
          encodeURIComponent(Base64.encode(url)) +
          "&watermarkTxt=" +
          //水印内容
          encodeURIComponent("") +
          "&token=" +
          getToken();
        this.previewModal.visible = true;
        this.previewModal.loading = false;
      } else {
        this.viewFileModal.name = row.name;
        this.viewFileModal.fileList = fileList ?? [];
        this.viewFileModal.visible = true;
      }
    },

    //下载
    downloadFile(row) {
      const fileList = JSON.parse(row?.fileAddress ?? "[]");
      if (fileList.length == 0) {
        return;
      } else if (fileList.length == 1) {
        let { url } = fileList?.[0] ?? {};
        downloadDfs(url);
      } else {
        this.viewFileModal.name = row.name;
        this.viewFileModal.fileList = fileList ?? [];
        this.viewFileModal.visible = true;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.project-initiation-container {
  display: flex;
  flex-direction: column;
  background: #ffffff;
  border-radius: 6px;
  overflow: hidden;
  .initiation-header {
    height: 64px;
    border-bottom: 1px solid #d9d9d9;
    padding: 0 24px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    font-size: 20px;
    color: #333333;
    flex-shrink: 0;
  }
  .initiation-main {
    flex: 1;
    padding: 16px;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    .introduce-container {
      height: 150px;
      background: rgba(250, 250, 250, 0.5);
      border-radius: 0px 0px 0px 0px;
      border: 1px solid #ededed;
      margin-bottom: 16px;
      padding: 0 30px;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      justify-content: center;
      .data-item {
        display: flex;
        font-weight: 400;
        font-size: 14px;
        .label {
          color: #8a9295;
          flex-shrink: 0;
        }
        .value {
          color: #333333;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          overflow: hidden;
          text-overflow: ellipsis;
        }
      }
      .base-info {
        display: flex;
        flex-wrap: nowrap;
        justify-content: space-between;
        margin-bottom: 20px;
        .data-item {
          .value {
            -webkit-line-clamp: 1;
          }
        }
      }
      .remark {
        display: flex;
        flex-wrap: nowrap;
        justify-content: space-between;
        .data-item {
          .value {
            -webkit-line-clamp: 2;
          }
        }
      }
    }
    .file-container {
      flex: 1;
      background: rgba(250, 250, 250, 0.5);
      border: 1px solid #ededed;
      display: flex;
      overflow: hidden;
      padding: 32px 90px 32px 30px;
      box-sizing: border-box;
      .name {
        padding-top: 6px;
        color: #8a9295;
        line-height: 14px;
        flex-shrink: 0;
      }
      .tree-container {
        width: 300px;
        margin-right: 10px;
        background: #ffffff;
        border-radius: 4px 4px 4px 4px;
        border: 1px solid #d4d7d8;
        overflow: auto;
        overflow-x: hidden;
        position: relative;
        padding: 10px;
        box-sizing: border-box;
        /deep/.ant-tree {
          .ant-tree-node-content-wrapper {
            &:hover {
              .operate {
                .anticon {
                  display: inline-block !important;
                }
              }
            }
          }
          li {
            width: 100%;
            .ant-tree-node-content-wrapper {
              position: relative;
              width: calc(100% - 25px);
              padding: 0;
              .ant-tree-iconEle {
                color: #ffca28;
                font-size: 16px;
              }
              .ant-tree-title {
                overflow: hidden;
                display: inline-block;
                width: calc(100% - 26px);
                .custom-tree-title-warp {
                  display: flex;
                  width: 100%;
                  .title {
                    flex: 1;
                    overflow: hidden;
                    overflow: hidden;
                    white-space: nowrap;
                    text-overflow: ellipsis;
                  }
                  .operate {
                    flex-shrink: 0;
                    color: #8c8c8c;
                    .anticon {
                      display: none;
                      margin-right: 8px;
                      &:last-of-type {
                        margin-right: 0;
                      }
                    }
                    .add-file-button {
                      font-size: 15px;
                    }
                  }
                }
              }
            }
          }
        }
        .ant-empty {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
        }
      }
      .right-container {
        width: calc(100% - 352px);
        display: flex;
        flex-direction: column;
        .operate {
          margin-bottom: 12px;
        }
        .table-container {
          flex: 1;
          background: #ffffff;
          .table-file-name {
            .name {
              color: #606266 !important;
              &:hover {
                color: #54adff !important;
              }
            }
          }

          .files-icon {
            .disabled {
              color: #d4d7d8 !important;
            }
            .anticon {
              cursor: pointer;
              font-size: 18px;
              color: #1677ff;
              margin-right: 16px;
              &:last-of-type {
                margin-right: 0;
              }
            }
            .anticon-download,
            .anticon-cloud-upload {
              color: #239b53;
            }
          }
        }
      }
    }
  }
}
</style>
